<!-- eslint-disable @typescript-eslint/no-unused-vars -->
<!-- eslint-disable prettier/prettier -->
<template>
  <div>
    <div class="card content-box">
      <span class="text">班组管理</span>
      <el-divider></el-divider>
      <!--搜索-->
      <div class="mt-4" style="display: flex">
        <el-input v-model="input" style="max-width: 600px" placeholder="搜索班组" class="input-with-select">
          <template #prepend>
            <el-select v-model="select" placeholder="筛选" style="width: 115px">
              <el-option label="班组名" value="1" />
              <el-option label="班组Id" value="2" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="search"/>
          </template>
        </el-input>
        <el-button :icon="Close" :disabled="!input" @click="cancel"  style="margin-left: 10px"/>
      </div>
      <div style="width: 100%; display: flex; justify-content: start">
        <el-button type="primary" @click="add_group = true">添加班组</el-button>
      </div>
      <br />
      <!--展示机构列表-->
      <el-table :data="tableData" border class="custom-table" style="width: 100%">
        <el-table-column type="selection" :selectable="selected" width="55" />
        <el-table-column label="序号" fixed width="100" type="index"> </el-table-column>
        <el-table-column label="班组名称" prop="className"></el-table-column>
        <el-table-column label="创建时间" prop="classDate"></el-table-column>
        <el-table-column label="操作" width="200">
          <!--#default="{ row }"-->
          <template #default="{ row }">
            <el-button type="primary" @click="click_show(row)" size="small">编辑</el-button>
            <el-button type="danger" @click="delGroup(row)" size="small" >删除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="空空如也" />
        </template>
      </el-table>
      <br>
      <!--分页 后面要根据数据算-->
      <div style="width: 100%; display: flex; justify-content: end">
      <el-pagination
        :current-page="searchData.current"
        :page-size="searchData.limit"
        :total="total"
        :pager-count="7"
        layout="jumper, prev, pager, next, total"
        @current-change="getData"
      /></div>
    </div>

    <!--班组详情抽屉-->

    <el-drawer v-model="show_group" size="60%">
      <div>
        <!--班组信息-->
        <el-card style="max-width: 100%">
          <template #header>{{ group.className }}</template>
          <div class="common-layout">
            <el-container>
              <el-main>
                <el-descriptions title="" :column="3" border>
                  <el-descriptions-item label="班组名称" label-align="right">
                    {{ group.className }}
                  </el-descriptions-item>
                  <el-descriptions-item label="创建时间" label-align="right" align="center">
                    {{ group.classDate }}
                  </el-descriptions-item>
                </el-descriptions>
              </el-main>
            </el-container>
            <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="addMemClick" style="margin-bottom: 5px">新增用户</el-button>
            <el-table :data="members" style="width: 100%">
              <el-table-column label="序号" width="100" type="index"> </el-table-column>
              <el-table-column label="用户实名" prop="realName"></el-table-column>
              <el-table-column label="用户电话" prop="phone"></el-table-column>
              <el-table-column label="操作" width="200">
                <!--#default="{ row }"-->
                <template #default="{ row }">
                  <el-button type="danger" :icon="Delete" circle @click="delMember(row)" />
                </template>
              </el-table-column>
              <template #empty>
                <el-empty description="空空如也" />
              </template>
            </el-table>
          </div>
        </el-card>
      </div>

      <div></div>
    </el-drawer>

    <!--班组修改抽屉-->
    <!-- <el-drawer v-model="show_groDetail" title="班组信息" :append-to-body="true" size="50%">
    <el-form :model="groupForm" label-width="100px">
      <el-form-item label="班组名称" disabled>
        <el-input v-model="groupForm.className" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="editClick">修改</el-button>
        <el-button type="info" @click="show_groDetail = false">取消</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="members" style="width: 100%" border>
      <el-table-column prop="userId" label="用户Id">
        <template #default="scope">
          <el-input v-model="scope.row.userId" placeholder="请输入用户Id"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="danger" @click="deleteRow1(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-drawer> -->

    <!-- 添加班组弹窗 -->
    <el-dialog v-model="add_group" width="40%">
      <el-form :model="groupForm" label-width="130px" style="padding-right: 30px">
        <el-form-item label="班组名称">
          <el-input v-model="groupForm.className"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="add_group = false">取消</el-button>
          <el-button type="primary" @click="addGroup"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!--对话框，确定用-->
    <!-- <el-dialog v-model="isSure" title="Warning" width="500" align-center>
    <span>{{ sureContext }}</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isSure = false">取消</el-button>
        <el-button type="primary" @click="doNext"> 确认 </el-button>
      </div>
    </template>
  </el-dialog> -->

    <!--添加组员-->
    <el-dialog v-model="add_mem" title="添加组员" width="50%">
      <div>
        <el-table :data="addList" style="width: 100%" border>
          <el-table-column prop="userId" label="用户Id">
            <template #default="scope">
              <el-select v-model="scope.row.userId" placeholder="选择新组员" size="small">
                <el-option v-for="item in users" :key="item.userId" :label="item.realName" :value="item.userId" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="danger" @click="deleteRow1(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button @click="addRow1" type="primary" style="margin-top: 5px">添加行</el-button>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="add_mem = false">取消</el-button>
          <el-button type="primary" @click="addMember"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="departmentManage">
import { onMounted, reactive, ref } from "vue";
import { CirclePlus, Delete, Search, Close } from "@element-plus/icons-vue"; //, Edit
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getAllClassService,
  addClassMemberService,
  delClassMemberService,
  addClassService,
  delClassService,
  getClassMemberService
} from "@/api/systemManage/class";
import { classSearchService } from "@/api/systemManage/search";
import { getAllWorkerService } from "@/api/systemManage/user";

//控制变量
const add_group = ref(false);
//const show_groDetail = ref(false);
const show_group = ref(false);
//const isSure = ref(false);
//const sureContext = ref("");
const add_mem = ref(false);
const groupId = ref("");
//用户搜索输入
const input = ref("");
const select = ref();
//数据模型
const classes = ref([
  {
    classId: 0,
    className: "电安一组",
    classDate: "2024-1-20"
  }
]);
const searched = ref([
  {
    classId: 0,
    className: "电安一组",
    classDate: "2024-1-20"
  }
]);

//class不允许做变量名，用group代替
const group = ref({
  classId: 0,
  className: "电安一组",
  classDate: "2024-1-20"
});

//要根据班组查询旗下工人
const members = ref([
  {
    phone: "string",
    classId: -2147483648,
    realName: "string",
    realNameId: -2147483648,
    userId: 0
  }
]);

interface userListItem {
  userId: number | String;
}
//添加组员
const addList = ref<[userListItem]>([
  {
    userId: ""
  }
]);
const clearAddList = () => {
  addList.value = [
    {
      userId: ""
    }
  ];
};
const newList = ref<number[]>([]);

// 函数将 addList 中的 userId 提取到 newList
const changeTo = () => {
  // 使用 filter 和 map 提取 userId，并过滤掉 null 或 undefined
  newList.value = addList.value
    .map(item => item.userId) // 提取 userId
    .filter((id): id is number => id !== null); // 过滤 null 值，并确保类型为 number
  console.log(newList.value);
};

const groupForm = ref({
  className: ""
});

//分页
const total = ref(classes.value.length);
// searchData-向后端分页查询的对象，即当前页和每页总数
const searchData = reactive({
  current: 1,
  limit: 7
});

const tableData = ref([{}]);

//传入分页参数
const pageQuery = (current, limit) => {
  let begin = current * limit - limit;
  //这里不减一是因为，slice方法裁切是左闭右开数组
  let end = current * limit;
  tableData.value = classes.value.slice(begin, end);
};

const getData = newPage => {
  searchData.current = newPage;
  total.value = classes.value.length;
  pageQuery(searchData.current, searchData.limit);
};

const convertIsoToChineseDate = isoString => {
  const date = new Date(isoString);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，所以加1
  const day = date.getDate().toString().padStart(2, "0");
  return `${year}年${month}月${day}日`;
};

const getClassList = async () => {
  let result = await getAllClassService();
  classes.value = result.data.data;
  classes.value.forEach(item => {
    item.classDate = convertIsoToChineseDate(item.classDate);
  });
  getData(1);
};
onMounted(getClassList);

const getClassMember = async id => {
  let dataObj = {
    classId: id
  };
  let result = await getClassMemberService(dataObj);
  console.log("获得成员" + result);
  members.value = result.data.data;
};

const click_show = async row => {
  //console.log("当前" + id);
  groupId.value = row.classId;
  await getClassMember(row.classId);
  group.value = row;
  show_group.value = true;
};

const selected = () => {
  return true;
};

const users = ref([
  {
    phone: "",
    classId: -1,
    realName: "",
    realNameId: "",
    userId: -1,
    username: "",
    email: "",
    role: ""
  }
]);

const makeList = async () => {
  clearAddList();
  let result = await getAllWorkerService();
  users.value = result.data.data.filter(item => item.classId === -1);
  if (users.value.length === 0) ElMessage.warning("当前无空闲用户可添加");
};

const addGroup = async () => {
  const result = await addClassService(groupForm.value);
  if (result.data.code === 0) {
    ElMessage.success("新增班组成功");
    add_group.value = false;
    getClassList();
  } else {
    ElMessage.error("新增失败：" + result.data.message);
  }
};

const addMember = async () => {
  changeTo();
  let dataObj = {
    classId: groupId.value,
    userIdList: newList.value
  };
  console.log(dataObj);
  await addClassMemberService(dataObj);
  getClassMember(groupId.value);
  add_mem.value = false;
};

const delGroup = async row => {
  ElMessageBox.confirm("确认删除该班组?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    let dataObj = {
      classId: row.classId
    };
    const res = await delClassService(dataObj);
    if (res.data.code === 0) {
      ElMessage.success("删除成功");
      await getClassList();
    } else {
      ElMessage.error("删除失败：" + res.data.message);
    }
  });
};

const delMember = async row => {
  ElMessageBox.confirm("确认删除该成员?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    let dataObj = {
      classId: row.classId,
      userId: row.userId
    };
    const res = await delClassMemberService(dataObj);
    if (res.data.code === 0) {
      await getClassMember(groupId.value);
      ElMessage.success("删除成功");
    } else {
      ElMessage.error("删除失败：" + res.data.message);
    }
  });
};

const deleteRow1 = item => {
  const index = item;
  if (index !== -1) {
    addList.value.splice(index, 1);
  }
};

const addRow1 = () => {
  addList.value.push({
    userId: 0
  });
};

//搜索
const search = async () => {
  let dataObj = {
    className: "",
    classId: -1
  };
  if (select.value == 1) {
    dataObj.className = input.value;
  } else if (select.value == 2) {
    dataObj.classId = +input.value;
  }
  let result = await classSearchService(dataObj);
  console.log(result);
  searched.value = result.data.data;
  searched.value.forEach(item => {
    item.classDate = convertIsoToChineseDate(item.classDate);
  });
  tableData.value = searched.value;
};

const cancel = () => {
  input.value = "";
  tableData.value = classes.value;
};

const addMemClick = () => {
  add_mem.value = true;
  makeList();
};

// const submitForm = async () => {
//   ElMessage.success(groupForm.value.class_name + "submit success");
// };

// const doNext = async () => {
//   if (isSure.value) {
//     if (sureContext.value == "确定提交当前修改？") {
//       submitForm();
//       isSure.value = false;
//       show_groDetail.value = false;
//     }
//   }
// };
</script>

<style scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  font-size: 32px;
  font-weight: 600;
  color: #6b778c;
}
.demo-tabs {
  margin-top: -20px;
}
.topadd {
  position: absolute;
  top: 73px;
  right: 40px;
}
.page-container {
  box-sizing: border-box;
  min-height: 100%;
}
.add {
  position: absolute;
  top: 80%;
  right: 3%;
  float: left;
  width: 60px;
  height: 60px;
  font-size: 50px;
  font-weight: 600;
  border-radius: 50%;
}
.inneradd {
  position: absolute;
  top: 55px;
  right: 30px;
  float: left;
  font-weight: 900;
}
.avatar-uploader .avatar {
  display: block;
  width: 178px;
  height: 178px;
}
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #060707;
  text-align: center;
}
:deep(.my-label) {
  background: var(--el-color-success-light-9) !important;
}
:deep(.my-content) {
  background: var(--el-color-danger-light-9);
}
.Product-image {
  width: auto; /* 图片宽度自适应 */
  max-width: 100%; /* 图片最大宽度为其容器的100% */
  height: auto; /* 图片高度自适应 */
  max-height: 100%; /* 图片最大高度为其容器的100% */
}
.custom-table :deep(.el-table__header-wrapper thead tr th) {
  color: #000000;
  text-align: center;
  background-color: #fafafa;
}
.custom-table :deep(.el-table__body-wrapper tbody tr td) {
  text-align: center; /* 单元格内容居中 */
}
</style>
